import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc

from dash.dependencies import Input, Output, State

from ..api_client import APIClient
from ..app import app


content = dbc.Container([
    html.H2('注册'),
    dcc.Location(id='register-location', refresh=True),
    dbc.Container([
        html.Div([
            dbc.Container(id='register-form', children=[
                dcc.Input(placeholder='邮箱',
                          type='email',
                          id='register-email-input',
                          className='form-control'),
                html.Br(),
                dcc.Input(placeholder='姓氏',
                          type='text',
                          id='register-lastname-input',
                          className='form-control'),
                html.Br(),
                dcc.Input(placeholder='名字',
                          type='text',
                          id='register-firstname-input',
                          className='form-control'),
                html.Br(),
                dcc.Input(placeholder='密码',
                          type='password',
                          id='register-password-input',
                          className='form-control'),
                html.Br(),
                html.Button(children='注册',
                            type='submit',
                            id='register-btn',
                            className='btn btn-primary btn-lg'),
                html.Br()],
                className='form-group')])],
        className='jumbotron')])


@app.callback(
    Output('register-location', 'pathname'),
    Input('register-btn', 'n_clicks'),
    State('register-email-input', 'value'),
    State('register-password-input', 'value'),
    State('register-firstname-input', 'value'),
    State('register-lastname-input', 'value'))
def on_submit_signup_form(n_clicks, email, password, firstname, lastname):
    if not n_clicks:
        raise dash.exceptions.PreventUpdate('stop')

    client = APIClient()
    response = client.register(email, password, firstname, lastname)

    if response.status_code == 200:
        payload = response.json()
        dash.callback_context.response.set_cookie('access_token', payload['access'])
        return '/home'

    return '/register'
